package com.components;

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.utility.MousePress;
import com.utility.Point;

public class Server implements Runnable {
	private boolean running;
	private final ServerSocket s;
	private Robot robot;

	public Server(final ServerSocket s) {
		this.s = s;		
		try {
			robot = new Robot();		
		} catch (final AWTException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		running = true;
		System.out.println("Server started.");

		try {
			while (true) {
				final Socket socket = s.accept();
				final RemoteTask r = new RemoteTask(socket);
				new Thread(r).start();
			}
		} catch (final IOException e1) {
			e1.printStackTrace();
		}
	}

	public boolean isRunning() {
		return running;
	}

	class RemoteTask implements Runnable {
		private final Socket socket;

		public RemoteTask(final Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			try {
				if (socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown()) {
					return;
				}

				final InputStream is = socket.getInputStream();
				if (is.available() != 0) {
					final ObjectInputStream ois = new ObjectInputStream(is);
					
					final Object object = ois.readObject();
					if(object instanceof Point) {
						final Point point = (Point)object;
						final int dx = point.getX();						
						final int dy = point.getY();
						System.out.println(dx + "; " + dy);
						moveMouseByDelta(dx, dy);
					} else if(object instanceof MousePress) {
						final MousePress press = (MousePress)object;
						System.out.println("Press");
						if(press.isLeftPress()) {
							System.out.println("Left press");
							doLeftPress();
						} else if(press.isRightPress()) {
							System.out.println("Right press");
							doRightPress();
						}
					}
				}
				socket.close();
			} catch (final IOException e) {
				e.printStackTrace();
			} catch (final ClassNotFoundException e) {
				e.printStackTrace();
			}
		}

		private void moveMouseByDelta(final int dx, final int dy) {
			final java.awt.Point p = MouseInfo.getPointerInfo().getLocation();
			final int currentX = p.x;
			final int currentY = p.y;
			robot.mouseMove(currentX + dx, currentY + dy);
		}
		
		private void doLeftPress() {
			robot.mousePress(InputEvent.BUTTON1_MASK);
		}
		
		private void doRightPress() {
			robot.mousePress(InputEvent.BUTTON3_MASK);
		}
	}

}
